package com.cn.sys.main.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cn.sys.frame.dao.BaseSpringJdbcDao;
import com.cn.sys.frame.service.impl.BaseServiceImpl;
import com.cn.sys.frame.util.query.QueryBean;
import com.cn.sys.frame.util.query.QueryCondition;
import com.cn.sys.main.dao.SysFunctionDao;
import com.cn.sys.main.entity.SysFunction;
import com.cn.sys.main.service.SysFunctionService;

@Service("sysFunctionService")
public class SysFunctionServiceImpl extends BaseServiceImpl<SysFunction, Long> implements
		SysFunctionService {

	private SysFunctionDao sysFunctionDao;
	
	@Autowired
	public void setBaseDao(BaseSpringJdbcDao<SysFunction, Long> sysFunctionDao) {
		this.baseDao = sysFunctionDao;
		this.sysFunctionDao = (SysFunctionDao) sysFunctionDao;
	}

	public List<SysFunction> getFunctionsByModuleId(String moduleId) throws Exception{
		QueryCondition queryCondition = new QueryCondition();
		if(StringUtils.isNotBlank(moduleId)){
			QueryBean qb = new QueryBean(" AND MODULE_ID = ?", "MODULE_ID", Long.valueOf(moduleId));
			queryCondition.setQueryBean(qb);
		}
		QueryBean qb = new QueryBean(" AND TYPE = ?", "TYPE", "2");
		queryCondition.setQueryBean(qb);
		queryCondition.setOrderSql(" ORDER BY ORDER_INDEX ASC");
		return sysFunctionDao.listByCondition(queryCondition);
	}

	public List<SysFunction> getFunctionsByUserId(Long userId) throws Exception{
		List<SysFunction> list = null;
		if(userId==null){
			String sql = "SELECT ID,NAME,FUNCTION_CODE,URL,TYPE,MODULE_ID FROM SYS_FUNCTION WHERE TYPE = '2' OR TYPE = '3' ORDER BY MODULE_ID ASC";
			list = sysFunctionDao.listBySql(sql, new Object[0]);
		}else {
			String sql = "SELECT * FROM (SELECT DISTINCT T3.ID, T3.NAME,T3.FUNCTION_CODE,T3.URL,T3.TYPE, T3.MODULE_ID " +
					"FROM SYS_USER_ROLE T1, SYS_ROLE_FUNCTION T2, SYS_FUNCTION T3 WHERE T1.ROLE_ID = T2.ROLE_ID " +
					"AND T2.FUNCTION_ID = T3.ID AND T1.USER_ID = ?) TEMP " +
					"UNION ALL SELECT T3.ID, T3.NAME,T3.FUNCTION_CODE,T3.URL,T3.TYPE, T3.MODULE_ID FROM SYS_FUNCTION T3, SYS_USER_ROLE T4, SYS_ROLE_MODULE T5" +
					" WHERE T4.USER_ID=? AND T4.ROLE_ID=T5.ROLE_ID AND T5.MODULE_ID = T3.MODULE_ID AND T3.TYPE = '3'";
			list = sysFunctionDao.listBySql(sql, userId, userId);
		}
		return list;
	}

	public List<SysFunction> getPublicFunctions() throws Exception{
		QueryCondition queryCondition = new QueryCondition();
		QueryBean qb = new QueryBean(" AND TYPE = ?", "TYPE", "1");
		queryCondition.setQueryBean(qb);
		return sysFunctionDao.listByCondition(queryCondition);
	}

}
